package com.mrzhou.auth.authorzation.impl;

import com.mrzhou.auth.authorzation.AbstractIntegrationAuthentication;
import com.mrzhou.auth.constant.AuthConstant;
import com.mrzhou.auth.exception.IntegrationException;
import com.mrzhou.auth.service.CloudUserDetails;
import com.mrzhou.auth.support.IntegrationAuthenticationEntity;
import com.mrzhou.auth.support.SimpleUser;
import com.mrzhou.auth.utils.TokenUtil;
import com.mrzhou.common.entity.system.UserInfo;
import com.mrzhou.common.feign.client.IUserClient;
import com.mrzhou.core.tool.api.R;
import com.mrzhou.data.support.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 自定义的授权码登录方式,
 *  使用场景: 第三方登录集成
 */
@Component
@Slf4j
public class AuthCodeAuthentication extends AbstractIntegrationAuthentication {

    @Autowired
    private RedisService redisService;
    @Autowired
    private IUserClient userClient;

    @Override
    public CloudUserDetails authentication(IntegrationAuthenticationEntity authEntity) throws IntegrationException {
        String key = AuthConstant.REDIS_PREFIX_AUTH_CODE + authEntity.getClientId() + ":" + authEntity.getAuthParameter(TokenUtil.AUTH_CODE);
        SimpleUser simpleUser = redisService.get(key, SimpleUser.class);
        // 删除授权码, 使授权码只能使用一次
        redisService.remove(key);
        if(simpleUser == null) {
            throw new IntegrationException("授权码未获取, 或授权码填写错误！");
        }
        // 获取用户的基本信息
       R<UserInfo> result = userClient.userInfoById(simpleUser.getUserId());
        if(result.isSuccess()) {
            return CloudUserDetails.createCloudUserDetails(result.getData());
        }
        throw new IntegrationException(result.getMsg());
    }

    @Override
    public void prepare(IntegrationAuthenticationEntity authEntity) throws IntegrationException {

    }

    @Override
    public boolean support(IntegrationAuthenticationEntity authEntity) {
        return TokenUtil.AUTH_CODE.equals(authEntity.getAuthType());
    }
}
